package pers.byxiaobai.levelhealth.runnables;

import java.util.Collection;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import pers.byxiaobai.levelhealth.config.ConfigData;
import pers.byxiaobai.levelhealth.data.PlayerData;
import pers.byxiaobai.levelhealth.data.PlayerDataManager;
import pers.byxiaobai.levelhealth.message.MessageManager;
import pers.byxiaobai.levelhealth.permission.PermissionManager;
import pers.byxiaobai.levelhealth.utils.PlayerHealthUtil;

/** 
* @author byxiaobai
* 类说明 
*/
public class HealthRefreshRunnable extends BukkitRunnable{
	@Override
	public void run() {
		Collection<? extends Player> players=Bukkit.getOnlinePlayers();
		for(Player player:players) {
			PlayerData playerData=PlayerDataManager.INSTANCE.getPlayerData(player);
			//判断添加血量正确性
			double playerNowMaxHealth=PlayerHealthUtil.getPlayerMaxHealth(player);
			if(playerNowMaxHealth!=playerData.playerBaseHealth+playerData.addedHealth) {
				double changeValue=playerNowMaxHealth-playerData.playerBaseHealth-playerData.addedHealth;//血量变化的值
				playerData.playerBaseHealth+=changeValue;
			}
			//判断权限
			if(!PermissionManager.INSTANCE.hasUsePermission(player)) {
				if(playerData.addedHealth>0) {
					PlayerHealthUtil.setPlayerMaxHealth(player, playerData.playerBaseHealth);
					playerData.addedHealth=0;
				}
				continue;
			}
			
			boolean isAddedHealth=PlayerDataManager.INSTANCE.isPlayerAddedHealth(player);//是否已添加血量
			if(!isAddedHealth) {
				addPlayerHealth(player,playerData);
				doHealthScale(player);
				PlayerDataManager.INSTANCE.setIsAddedHealth(player, true);;
			}
		}
	}
	/**
	 * 给玩家添加血量
	 * @param player
	 */
	private void addPlayerHealth(Player player,PlayerData playerData) {
		int level=player.getLevel();
		double addHealth=ConfigData.INSTANCE.ADD_HEALTH_EACH_LEVEL*level;//将要添加的血量
		playerData.addedHealth=addHealth;
		double maxHealth=playerData.playerBaseHealth+addHealth;//获取玩家最大血量
		PlayerHealthUtil.setPlayerMaxHealth(player, maxHealth);
		if(ConfigData.INSTANCE.IS_LEVEL_UP_MESSAGE_ENABLE) {//如果升级提示开启
			MessageManager.INSTANCE.sendLevelUpMessage(player);
		}
	}
	/**
	 * 血量压缩
	 * @param player
	 */
	@SuppressWarnings("deprecation")
	private void doHealthScale(Player player) {
		if(player==null||!ConfigData.INSTANCE.IS_ENABLE_HEALTH_SCALE)return;
		double scaleValue=ConfigData.INSTANCE.HEALTH_SCALE_VALUE;
		if(player.getMaxHealth()>scaleValue) {
			player.setHealthScale(scaleValue);
		}
	}
}